<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="应用场景编号" prop="sceneId" label-width="100px">
        <el-input
          v-model="queryParams.sceneId"
          placeholder="请输入应用场景编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="运行环境(python、drools、groovy.)" prop="runEnv">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.runEnv"-->
      <!--          placeholder="请输入运行环境(python、drools、groovy.)"-->
      <!--          clearable-->
      <!--          size="small"-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="校验通过状态(1:通过0:不通过)" prop="state">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.state"-->
      <!--          placeholder="请输入校验通过状态(1:通过0:不通过)"-->
      <!--          clearable-->
      <!--          size="small"-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="插入时间" prop="insertTime">-->
      <!--        <el-date-picker clearable size="small"-->
      <!--          v-model="queryParams.insertTime"-->
      <!--          type="date"-->
      <!--          value-format="yyyy-MM-dd"-->
      <!--          placeholder="选择插入时间">-->
      <!--        </el-date-picker>-->
      <!--      </el-form-item>-->
      <el-form-item label="用户编号" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ruleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="规则编号" align="center" prop="id"/>
      <el-table-column label="应用场景编号" align="center" prop="sceneId"/>
      <el-table-column label="名称" align="center" prop="name"/>
      <el-table-column label="脚本类型" align="center">
        <template v-if="scope.row.scriptType !== undefined && scope.row.scriptType !== null" slot-scope="scope">
          <span>{{scriptTypeList[scope.row.scriptType]}}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="运行环境" align="center" prop="runEnv"/>-->
      <!--      <el-table-column label="运行脚本" align="center" prop="runScript" />-->
      <el-table-column label="校验通过状态" align="center" >
        <template v-if="scope.row.state !== undefined" slot-scope="scope">
          <span>{{scope.row.state === 1 ? '通过' : '不通过'}}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="插入时间" align="center" prop="insertTime" width="180">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ parseTime(scope.row.insertTime, '{y}-{m}-{d}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="用户编号" align="center" prop="userId"/>
      <!--      <el-table-column label="序号" align="center" prop="priority" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="execute(scope.row)"
          >执行脚本
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改规则信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" v-if="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="应用场景编号" prop="sceneId">
          <el-input v-model="form.sceneId" placeholder="请输入应用场景编号（输入完按回车键，加载输入参数）"
                    @keyup.enter.native="getParamListBySceneId(form.sceneId)"/>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"/>
        </el-form-item>
<!--        <el-form-item label="运行环境" prop="runEnv">-->
<!--          <el-input v-model="form.runEnv" placeholder="请输入运行环境(python、drools、groovy)"/>-->
<!--        </el-form-item>-->
        <el-form-item label="输入参数" prop="inputParameter">
          <el-input v-model="form.inputParameter" disabled/>
        </el-form-item>
        <el-form-item label="输出参数" prop="outputParameter">
          <el-input v-model="form.outputParameter" disabled/>
        </el-form-item>

        <el-form-item label="脚本类型" prop="scriptType">
          <el-select v-model="form.scriptType" placeholder="请选择类型" clearable size="small">
            <el-option label="公式" :value="0" />
            <el-option label="条件" :value="1" />
            <el-option label="自定义" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="运行脚本" prop="runScript">
          <el-input v-model="form.runScript" :rows="5" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <!--        <el-form-item label="校验通过状态(1:通过0:不通过)" prop="state">-->
        <!--          <el-input v-model="form.state" placeholder="请输入校验通过状态(1:通过0:不通过)" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="插入时间" prop="insertTime">-->
        <!--          <el-date-picker clearable size="small"-->
        <!--            v-model="form.insertTime"-->
        <!--            type="date"-->
        <!--            value-format="yyyy-MM-dd"-->
        <!--            placeholder="选择插入时间">-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="用户编号" prop="userId">-->
        <!--          <el-input v-model="form.userId" placeholder="请输入用户编号" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="序号" prop="priority">-->
        <!--          <el-input v-model="form.priority" placeholder="请输入序号" />-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 执行脚本弹窗 -->
    <el-dialog title="执行脚本" :visible.sync="openExecute" v-if="openExecute"  width="1200px" append-to-body>
      <el-form ref="scriptForm" :model="scriptForm" :rules="scriptRules" label-width="80px">
<!--        <el-form-item label="应用场景名称" prop="sceneName">-->
<!--          <el-input v-model="scriptForm.sceneName" disabled/>-->
<!--        </el-form-item>-->
        <el-form-item label="运行脚本" prop="scriptName">
          <el-input v-model="scriptForm.scriptName" disabled/>
        </el-form-item>

        <el-form-item label="脚本类型" prop="scriptType">
          <el-select v-model="scriptForm.scriptType" disabled>
            <el-option label="公式" :value="0" />
            <el-option label="条件" :value="1" />
            <el-option label="自定义" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="脚本内容" prop="scriptContent">
          <el-input v-model="scriptForm.runScript" :rows="5" type="textarea" placeholder="请输入内容"/>
        </el-form-item>


        <el-form-item label="输入参数" prop="inputParameter">
          <el-input v-model="scriptForm.inputParameter" disabled/>
        </el-form-item>
        <el-form-item label="输入变量" prop="variable" v-if="scriptForm.inputParameter">
          <el-input v-model="scriptForm.variable" placeholder="请输入参数,格式：参数1、参数2"/>
        </el-form-item>
        <el-form-item label="输出参数" prop="outputParameter">
          <el-input v-model="scriptForm.outputParameter" disabled/>
        </el-form-item>
        <el-form-item label="说明" prop="illustrate">
          <el-input v-model="scriptForm.illustrate" :rows="3" type="textarea" disabled/>
        </el-form-item>
        <el-form-item label="输出结果" prop="result">
          <el-input v-model="scriptForm.result" :rows="5" type="textarea"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="executeSubmitForm">确 定</el-button>
        <el-button @click="executeCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {listRule, getRule, delRule, addRule, updateRule} from "@/api/expert/rule";
  import {listParam} from "@/api/expert/param";
  import {execute} from "@/api/expert/circuit";

  export default {
    name: "Rule",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 规则信息表格数据
        ruleList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层
        openExecute: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          sceneId: null,
          name: null,
          runEnv: null,
          runScript: null,
          state: null,
          insertTime: null,
          userId: null,
          priority: null
        },
        // 查询参数
        paramQueryParams: {
          pageNum: 1,
          pageSize: 99999,
          name: null,
          type: null,
          priority: null,
          sceneId: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        // 表单参数
        scriptForm: {
          sceneId: '',
          sceneName: '',
          ruleId: '',
          inputParameter: '',
          outputParameter: '',
          variable: '',
          scriptContent: '',
          scriptName: '',
          illustrate: '',
          scriptType: '',
        },
        // 表单校验
        scriptRules: {},

        // 单行数据
        selectRow: null,

        // scriptTypeList
        scriptTypeList:["公式", "条件", "自定义"],
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询规则信息列表 */
      getList() {
        this.loading = true;
        listRule(this.queryParams).then(response => {
          this.ruleList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      getParamListBySceneId(sceneId) {
        this.$set(this.form, 'inputParameter', '')
        this.$set(this.form, 'outputParameter', '')
        this.paramQueryParams.sceneId = sceneId
        listParam(this.paramQueryParams).then(response => {
          if (response.rows) {
            console.log(response.rows)
            let inputParameter = ""
            let outputParameter = ""

            for (let i = 0; i < response.rows.length; i++) {
              if (response.rows[i].dataType === 1){
                inputParameter = inputParameter + response.rows[i].code + "、"
              }else if (response.rows[i].dataType === 2){
                outputParameter = outputParameter + response.rows[i].code + "、"
              }

            }
            this.$set(this.form, 'inputParameter', inputParameter)
            this.$set(this.form, 'outputParameter', outputParameter)

          }
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          sceneId: null,
          name: null,
          runEnv: null,
          runScript: null,
          state: null,
          insertTime: null,
          userId: null,
          priority: null,
          illustrate: '',
          scriptType: '',
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加规则信息";
        // this.form.inputParameter = ''
        // this.form.outputParameter = ''

      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getRule(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改规则信息";
          this.getParamListBySceneId(this.form.sceneId)
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateRule(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.form.state = 0
              addRule(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除规则信息编号为"' + ids + '"的数据项？').then(function () {
          return delRule(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('edsta/rule/export', {
          ...this.queryParams
        }, `edsta_rule.xlsx`)
      },
      /** 执行脚本弹窗 */
      execute(row) {
        this.selectRow = row
        this.openExecute = true
        this.scriptForm = {
          sceneId: row.sceneId,
          ruleId: row.id,
          sceneName: '',
          inputParameter: '',
          outputParameter: '',
          variable: '',
          result: '',
          runScript: row.runScript,
          scriptType: row.scriptType,
          scriptName : row.name,
          illustrate : '输入参数和输出参数都可用在条件上;\n输入参数的值为输入变量,是定义的变量;\n输出参数的值为元器件库;',
        }

        let paramQueryParams = {
          pageNum: 1,
          pageSize: 99999,
          name: null,
          type: null,
          priority: null,
          sceneId: row.sceneId,
          inputMinValue: null,
          inputMaxValue: null
        }
        listParam(paramQueryParams).then(response => {
          this.$set(this.scriptForm, 'inputParameter', '')
          this.$set(this.scriptForm, 'outputParameter', '')
          if (response.rows) {
            let inputParameter = ''
            let outputParameter = ''
            console.log(response.rows)
            for (let i = 0; i < response.rows.length; i++) {
              if (response.rows[i].dataType === 1){
                inputParameter = inputParameter + response.rows[i].code + "、"
              }else if(response.rows[i].dataType === 2){
                outputParameter = outputParameter + response.rows[i].code + "、"
              }
            } this.$set(this.scriptForm, 'inputParameter', inputParameter)
            this.$set(this.scriptForm, 'outputParameter', outputParameter)

          }
        });

      },
      /** 执行脚本 */
      executeSubmitForm() {
        this.$refs["scriptForm"].validate(valid => {
          if (valid) {
            // 先保存脚本，再运行脚本
            this.selectRow.runScript = this.scriptForm.runScript
            updateRule(this.selectRow).then(response => {
              execute(this.scriptForm.sceneId, this.scriptForm.ruleId, this.scriptForm.variable).then(response => {
                console.log("-----------")
                console.log(response)
                this.scriptForm.result = response.msg + '';
              },error => {
                console.log("---------------------------")
                console.log(error)
                this.scriptForm.result = error + '';
              });
            });

          }
        });
      },
      /** 取消 */
      executeCancel() {
        this.openExecute = false
        this.scriptForm = {
          id: null,
          name: null,
          state: null,
          insertTime: null,
          userId: null,
          path: null,
          scriptType: null
        };
        this.resetForm("scriptForm");
      }

    }
  };
</script>
